<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <div class="ccui-search-wrapper ccui-clearfix">
        <!--普通搜索Begin-->
        <div class="ccui-tab-wrapper">
          <el-button type="table-top-active" size="mini">应用角色</el-button>
        </div>
        <el-button
          size="mini"
          type="primary"
          icon="icon-ccui-add-sup"
          class="fr"
          ref="addjuese"
          @click="dialogAddRole"
          >新建角色
        </el-button>

        <!--普通搜索End-->
      </div>
    </div>

    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        :data="tableData"
        :fit="true"
        :max-height="tableMaxHeight"
        border
        class="multifunctional-table"
      >
        <el-table-column type="index" width="50" label="序号">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <template v-for="(table, index) in tableThead">
          <el-table-column
            v-if="table.checked"
            :fixed="table.fixed"
            :key="index"
            :label="table.label"
            :width="table.width"
            :min-width="table.width"
            :prop="table.prop"
            :show-overflow-tooltip="true"
            :formatter="table.formatter"
          >
          </el-table-column>
        </template>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="myscope">
            <el-button
              ref="powerManage-powerManageMaintain"
              size="mini"
              type="text"
              @click="handleGoMaintain(myscope.$index, myscope.row)"
              >权限维护
            </el-button>

            <el-button
              size="mini"
              type="text"
              v-if="chengyuanfc(myscope.row.roleId)"
              @click="handleGoMember(myscope.$index, myscope.row)"
              ref="powerManage-powerManageMemberMaintain"
              >成员维护
            </el-button>
            <el-button v-else size="mini" disabled type="text"
              >成员维护
            </el-button>
            <el-button
              v-if="changeRole(myscope.row['roleType'])"
              size="mini"
              type="text"
              @click="handleEditRole(myscope.$index, myscope.row)"
              >编辑
            </el-button>
            <el-button v-else size="mini" type="text" disabled>编辑 </el-button>
            <el-button
              v-if="changeRole(myscope.row['roleType'])"
              size="mini"
              type="text"
              @click="handleDeleteRole(myscope.$index, myscope.row)"
              >删除
            </el-button>
            <el-button v-else size="mini" type="text" disabled>删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      title="新建角色"
      :visible.sync="dialogVisible"
      width="430px"
      v-if="switchOn === 1"
      :before-close="closeDialog"
    >
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
          label="角色名称："
          prop="roleName"
          :label-width="labelwidth"
        >
          <el-input
            v-model="form.roleName"
            maxlength="20"
            style="width: 160px"
            placeholder="请输入角色名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述："
          prop="roleDesc"
          :label-width="labelwidth"
        >
          <el-input
            v-model="form.roleDesc"
            style="width: 260px"
            maxlength="100"
            placeholder="应用自定义角色"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click="closeDialog"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="addRoleInfo()"
          v-if="switchOn === 1"
          >确定</el-button
        >
        <el-button size="mini" type="primary-font-mini" v-else>确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑角色"
      :visible.sync="dialogVisible3"
      width="430px"
      v-if="switchOn === 2"
      :before-close="closeDialog3"
    >
      <el-form :model="form2" :rules="rules" ref="form">
        <el-form-item
          label="角色名称："
          prop="roleName"
          :label-width="labelwidth"
        >
          <el-input
            v-model="form2.roleName"
            maxlength="20"
            style="width: 160px"
            placeholder="请输入角色名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="角色描述："
          prop="roleDesc"
          :label-width="labelwidth"
        >
          <el-input
            v-model="form2.roleDesc"
            style="width: 260px"
            maxlength="100"
            placeholder="应用自定义角色"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click="closeDialog3"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="editRoleInfo()"
          v-if="switchOn === 2"
          >确定</el-button
        >
        <el-button size="mini" type="primary-font-mini" v-else>确定</el-button>
      </span>
    </el-dialog>
    <!--el-dialog title="编辑角色"
               :visible.sync="dialogVisible3"
               width="430px"
               :before-close="closeDialog3">
      <el-form :model="form2" :rules="rules" ref="form">
        <el-form-item label="角色名称：" prop="oldRoleName" :label-width="labelwidth">
          <div class="imitate2Input" style="width: 128px;">{{form2.oldRoleName||''}}</div>
        </el-form-item>
        <el-form-item label="变更为：" prop="roleName" :label-width="labelwidth">
          <el-input v-model="form2.roleName" maxlength="20" style="width: 160px" placeholder="请输入新角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述：" prop="roleDesc" :label-width="labelwidth">
          <el-input v-model="form2.roleDesc" style="width: 260px"   maxlength="100"  placeholder="应用自定义角色"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button size="mini" type="default-mini" @click="closeDialog3">取消</el-button>
    <el-button size="mini" type="primary-font-mini" @click="editRoleInfo()" v-if="switchOn===2">确定</el-button>
    <el-button size="mini" type="primary-font-mini" v-else>确定</el-button>
  </span>
    </el-dialog-->

    <el-dialog
      title="确认删除"
      :visible.sync="dialogVisible2"
      width="300px"
      show-divider
      show-shadow
      :before-close="handleClose2"
      custom-class="el-dialog--customize"
    >
      <span>{{ tips.deleteRoleTip }}</span>
      <span slot="footer">
        <el-button size="mini" type="default-mini" @click="closeDialog2"
          >取消</el-button
        >
        <el-button
          size="mini"
          type="primary-font-mini"
          @click="doneDeleteRole()"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAppRole,
  addRoleInfo,
  editRoleApi,
  findRole,
  deleteRoleApi
} from "../api/powerManage";
import getPower from "@/basa/utils/getPower.js";
import getMenuaa from "../mixins/getMenu.js";
export default {
  name: "powerManageList",
  mixins: [getPower, getMenuaa],
  computed: {
    changeRole(roleType, flag) {
      return function(roleType, flag) {
        /** do something */
        if (flag) {
          return roleType !== 1 && roleType !== 0 && this.isShowqx;
        } else {
          return roleType !== 1 && roleType !== 0;
        }
      };
    }
  },
  data() {
    return {
      orgAdmin: false,
      branchAdmin: false,
      appAdmin: false,
      liuchengAdmin: false,
      deleteRoleName: "",
      deleteRoleId: "", // 需要删除的角色id
      dialogVisible2: false, // 删除提示框
      dialogVisible: false, // 新建角色弹框开关
      dialogVisible3: false, // 编辑角色弹框开关
      applicationId: 106, // 应用id 值106是组织管理
      appPermissionId: "", // 应用授权id
      // 表格最大高度
      tableMaxHeight: 0,
      // 表格数据
      tableData: [],
      // 表格命名
      tableName: this.tableList.powerManageList,
      // 表格数据
      tableThead: [
        {
          label: "AgentID",
          prop: "appId",
          width: "150",
          checked: true,
          fixed: false
        },
        {
          label: "应用",
          prop: "appName",
          width: "120",
          checked: true,
          fixed: false
        },
        {
          label: "角色名称",
          prop: "roleName",
          width: "120",
          checked: true,
          fixed: false
        },
        {
          label: "角色描述",
          prop: "description",
          width: "200",
          checked: true,
          fixed: false
        },
        {
          label: "用户列表",
          prop: "users",
          width: "auto",
          checked: true,
          fixed: false,
          formatter: function(row, column, cellValue) {
            var users = cellValue.map(({ name }) => name);
            return users.join(" ");
          }
        }
      ],
      isFocus: 1,
      totalNum: 0,
      isShow: false,
      pageNo: 1,
      labelwidth: "82px", // 弹窗中lable宽度
      switchOn: 1, // 新建角色 开关
      form: {
        // 新建角色弹框数据存储
        roleName: "",
        roleDesc: ""
      },
      rules: {
        // 弹窗中input必填规则
        roleName: [
          {
            required: true,
            message: "请输入角色名称",
            trigger: "blur"
          }
        ]
      },
      form2: {
        // 修改角色弹框数据存储
        oldRoleName: "",
        roleId: "",
        roleName: "",
        roleDesc: ""
      },
      isShowqx: true,
      isShowcy: true
    };
  },
  mounted() {
    this.isShowcy = this.getPower(
      "powerManage-powerManageMemberMaintain",
      true
    );
    // this.getPower("addjuese")
    this.isShowqx = this.getPower("powerManage-powerManageMaintain", true);
    // console.log(this.isShowqx);
    // console.log(this.isShowcy);
    // 自动获取表格高度
    this.$nextTick(() => {
      this.computeTableHeight();
    });
    // 浏览器调整大小时，表格高度实时改变
    window.onresize = () => {
      this.computeTableHeight();
    };
    // this.$store.dispatch("closeSidebarTemporary");
    this.findRole();
    this.getlist();
  },
  methods: {
    fileUser(row, column) {
      // console.log(column);
    },
    handleGoMaintain(index, row) {
      // 进入权限维护
      this.$router.push(
        `/powerManage/powerManageMaintain/${row.roleId}/${row.roleType}`
      );
    },
    handleGoMember(index, row) {
      // 进入成员维护
      this.$router.push("/powerManage/powerManageMemberMaintain/" + row.roleId);
    },
    handleEditRole(index, row) {
      // 编辑角色
      this.form2.roleId = row.roleId;
      // console.log(this.form2.roleId);
      // this.form2.oldRoleName = row.roleName
      this.form2.roleName = row.roleName;
      this.form2.roleDesc = row.description;
      this.switchOn = 2;
      this.dialogVisible3 = true;
    },
    editRoleInfo() {
      this.form2.roleDesc =
        this.form2.roleDesc.trim() === ""
          ? "应用自定义角色"
          : this.form2.roleDesc.trim();
      this.form2.roleName = this.form2.roleName.trim();

      let obj = { isShowLoading: true };

      obj.roleId = this.form2.roleId;
      obj.roleName = this.form2.roleName.trim();
      obj.roleDesc = this.form2.roleDesc.trim();
      this.$refs["form"].validate(valid => {
        if (!valid) {
          // 验证不通过禁止提交
          // console.log("验证不通过");
          return false;
        } else {
          // this.switchOn = 0;
          editRoleApi(obj).then(res => {
            if (res.data.code === "0") {
              this.dialogVisible3 = false; // 关闭弹框
              this.form2 = {
                // 弹框数据存储
                roleId: "",
                oldRoleName: "",
                roleName: "",
                roleDesc: ""
              };
              // 重新请求getlist
              this.tip("编辑成功", true);
              this.getlist();
            }
          });
          // .catch(e => {
          //     //this.switchOn = 2;
          //     console.log(e)
          //     this.tip(e)
          // })
        }
      });
    },
    handleDeleteRole(index, row) {
      // 删除角色
      this.deleteRoleId = row.roleId;
      this.deleteRoleName = row.appName;
      this.dialogVisible2 = true;
    },
    tip(mssage, type, time) {
      this.$message({
        message: mssage || "未填写提示语言",
        type: type ? "success" : "error",
        duration: time || 3000,
        ccuiCustom: true,
        showClose: true,
        offset: document.body.clientHeight / 2 - 21
      });
    },
    doneDeleteRole() {
      let obj = {
        roleId: this.deleteRoleId,
        roleName: this.deleteRoleName,
        isShowLoading: true
      };
      deleteRoleApi(obj).then(res => {
        this.deleteRoleId = "";
        this.dialogVisible2 = false; // 关闭弹框
        // 重新请求getlist
        this.getlist();
        this.getMenu();
        // console.log(this.getMenu);

        this.tip("删除成功", true);
      });
      // .catch(e => {
      //     console.log(e)
      //     this.tip(e)
      // })
    },
    chengyuanfc(roleId) {
      if (this.orgAdmin) {
        return true;
      } else if (this.branchAdmin) {
        if (roleId === 100002) {
          return false;
        } else {
          return true;
        }
      } else if (this.appAdmin || this.liuchengAdmin) {
        if (
          roleId === 100002 ||
          roleId === 100004 ||
          roleId === 100005 ||
          roleId === 100001 ||
          !this.isShowcy
        ) {
          if (
            (roleId === 100005 && this.liuchengAdmin) ||
            (roleId === 100001 && this.appAdmin)
          ) {
            if (this.isShowcy) {
              return true;
            } else {
              return false;
            }
          } else {
            return false;
          }
        } else {
          return true;
        }
      } else {
        if (
          roleId === 100002 ||
          roleId === 100004 ||
          roleId === 100001 ||
          roleId === 100005 ||
          !this.isShowcy
        ) {
          return false;
        } else {
          return true;
        }
      }
    },
    handlePrev() {
      // console.log("上一页");
    },
    handleNext() {
      // console.log("下一页");
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      val !== "none" && (this.pageSize = val);
      this.getList();
    },
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.pageNo = val;
      this.getlist();
    },
    // 数据请求
    findRole() {
      findRole({}).then(res => {
        let roleIdArr = res.data.data.map(({ roleId }) => {
          return roleId;
        });
        // console.log(roleIdArr);
        // 100002 是组织管理员  100004 是分支管理员 id 不会轻易变更 所以可以写死
        this.orgAdmin = roleIdArr.includes(100002);
        this.branchAdmin = roleIdArr.includes(100004);
        this.appAdmin = roleIdArr.includes(100001);
        this.liuchengAdmin = roleIdArr.includes(100005);
        // console.log(this.appAdmin);
        // console.log(this.orgAdmin);
      });
      // .catch(e => {
      //     console.log(e)
      // })
    },
    getlist() {
      let obj = { qryAgentId: "100003@100003", isShowPageLoading: true };

      getAppRole(obj).then(res => {
        // console.log(res);
        this.tableData = res.data.data;
      });
      // .catch(e => {
      //     console.log(e)
      // })
    },
    addRoleInfo() {
      this.form.roleDesc = this.form.roleDesc.trim();
      this.form.roleName = this.form.roleName.trim();
      this.form.isShowLoading = true;
      this.$refs["form"].validate(valid => {
        if (!valid) {
          // 验证不通过禁止提交
          // console.log("验证不通过");
          return false;
        } else {
          //this.switchOn = 0;
          addRoleInfo(this.form).then(res => {
            if (res.data.code === "0") {
              this.dialogVisible = false; // 关闭弹框
              this.form = {
                // 弹框数据存储
                roleName: "",
                roleDesc: ""
              };
              this.tip("新建角色成功", true);
              // 重新请求getlist
              this.getlist();
            } else {
              this.tip(res.data.message);
            }
          });
          // .catch(e => {
          //     // this.switchOn = 1;
          //     this.tip(e)
          // })
        }
      });
    },
    dialogAddRole() {
      // 新建角色
      this.switchOn = 1;
      this.dialogVisible = true;
    },
    // 页面操作
    handleClose(done) {
      // 关闭弹框
      done();
      this.dialogVisible = false;
      this.form.roleId = "";
      this.form.roleName = "";
      this.form.roleDesc = "";
    },
    closeDialog() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
      this.form.roleId = "";
      this.form.roleName = "";
      this.form.roleDesc = "";
    },
    handleClose2(done) {
      done();
      this.deleteRoleId = "";
    },
    closeDialog2() {
      this.dialogVisible2 = false;
      this.deleteRoleId = "";
    },
    closeDialog3() {
      this.dialogVisible3 = false;
      this.form2.roleId = "";
      this.form2.oldRoleName = "";
      this.form2.roleName = "";
      this.form2.roleDesc = "";
    },
    // 计算表格高度方法
    computeTableHeight() {
      // 获取表格所占区域的总高度
      let appContainerHeight = document.documentElement.clientHeight - 100 - 40;
      // 获取搜索区域的高度
      let searchHeight = 40;
      // 减去为表格所占高度，-70为距底边留白区域
      this.tableMaxHeight =
        appContainerHeight - searchHeight - 70 > 0
          ? appContainerHeight - searchHeight - 70
          : 0;
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/config/styles/variables.scss";
/deep/ .el-dialog__body .el-form .el-form-item {
  margin-bottom: 20px;
}

.el-table__body-wrapper > .el-table__body {
  /*解决safari浏览器兼容*/
  table-layout: fixed !important;
}

.app-list-top {
  position: relative;
  padding: 0 0 18px 0;
}

.el-add-role {
  position: absolute;
  top: 0px;
  right: 0;
  padding: 0;
}
/deep/ .el-dialog__body {
  padding-top: 20px;
}
</style>
